﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO;
using System.ComponentModel.DataAnnotations;

namespace ProjectManagement
{
    public static class PMHelper
    {
        private static CollectionProjects _colProjects;
        private static Project _currentProject;

        public static CollectionProjects ColProjects
        {
            get { return _colProjects; }
            set { _colProjects = value; }
        }

        public static Project CurrentProject
        {
            get { return PMHelper._currentProject; }
            set { PMHelper._currentProject = value; }
        }

        public static CollectionProjects LoadProjects()
        {
            var stream = new StreamReader("projects.xml");
            var serializer = new XmlSerializer(typeof(CollectionProjects));
            _colProjects = (CollectionProjects)serializer.Deserialize(stream);
            stream.Close();
            return _colProjects;
        }

        public static Project LoadProject(string name)
        {
            foreach (var project in _colProjects.ColProjects)
            {
                if (project.Name == name)
                {
                    CurrentProject = project;
                }
            }

            return CurrentProject;
        }

        public static Project CreateProject(string name, string path)
        {
            try
            {
                Project newProject = Project.CreateProject(name, path);
                _colProjects.ValidateProject(newProject);

                _colProjects.ColProjects.Add(newProject);
                Directory.CreateDirectory(newProject.Path);
                var strea = new StreamWriter("projects.xml");
                var serializer = new XmlSerializer(typeof(CollectionProjects));
                serializer.Serialize(strea, _colProjects);
                strea.Close();
                _currentProject = newProject;
                return newProject;
            }
            catch (Exception ex)
            {
                throw new Exception(String.Format("Error al crear el proyecto. {0}", ex.Message), ex);
            }
        }
    }
}
